[Vue Router warn]: Discarded invalid param(s) “id“ when navigating. Seexxxxxxxfor more details
Warning message suggests links to visit
Scenes:
When I try to use name+params to route jump and pass parameters in the vue3 combined api, a warning message appears and the params parameters cannot be received. code show as below:
Page a jumps to page b
//page a
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const params = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
const toDetail = () => router.push({ name: 'detail', params })
</script>
<template>
<el-button type="danger" @click="toDetail">Show Detail</el-button>
</template>
//page b
<template>
<div>Name:{{ route.params?.name }}</div>
<div>Phone:{{ route.params?.phone }}</div>
<div>Age:{{ route.params?.age }}</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
</script>
Click the link to view the change log
In other words, after the 2022-8-22 update of Vue Router, we cannot obtain the new page using the above method:
Vue also proposed a solution for us:
Pass parameters using query method
Just change it to query parameter passing. When query parameter passing, you can write either path or name, and all parameters will be displayed on the URL address.
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const query = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
const toDetail = () => router.push({ path: '/detail', query })
</script>
<template>
<el-button type="danger" @click="toDetail">Show Detail</el-button>
</template>
Place the parameters in the pinia or vuex warehouse
Use dynamic route matching
If you need to pass fewer parameters, you can try the following method. Just modify the path definition part:
// params: { id: '1', name: 'ly', phone: 13246566476, age: 23 }
{
path: '/detail/:id/:name/:phone/:age',
name: 'detail',
component: () => import('@/views/detail/index.vue')
}
Check the page effect and the console warning has disappeared:
Note that if you use this dynamic route matching method,path: '/detail/:id/:name/:phone/:age' you must pass all three parameters in , otherwise an error will be reported:
[Pass state and use History API to receive parameters on the new page] (#Use History API to pass and receive)
Use the state parameter on the page before the jump: a jumps to b
//page a
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const params = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
const toDetail = () => router.push({ name: 'detail', state: { params } })
</script>
<template>
<el-button type="danger" @click="toDetail">Show Detail</el-button>
</template>
//page b
<template>
<div>{{ historyParams }}</div>
</template>
<script setup lang="ts">
const historyParams = history.state.params
console.log('history.state', history.state)
</script>